// Copyright (c) 2001 The Wilson Partnership.
// All Rights Reserved.
// @(#)MinMLSocketServer.java, 0.1, 6th July 2001
// Author: John Wilson - tug@wilson.co.uk

package uk.co.wilson.net;

/*
Copyright (c) 2001 John Wilson (tug@wilson.co.uk).
All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:

Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.

Redistributions in binary form must reproduce the
above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or
other materials provided with the distribution.

All advertising materials mentioning features or use
of this software must display the following acknowledgement:

This product includes software developed by John Wilson.
The name of John Wilson may not be used to endorse or promote
products derived from this software without specific prior
written permission.

THIS SOFTWARE IS PROVIDED BY JOHN WILSON ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JOHN WILSON
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE
*/

import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import java.io.InterruptedIOException;
import java.io.IOException;

public abstract class MinMLSocketServer implements Runnable
{
  public MinMLSocketServer(final ServerSocket serverSocket,
                           final int minWorkers,
                           final int maxWorkers,
                           final int workerIdleLife)
  {
    this.serverSocket = serverSocket;
    this.minWorkers = Math.max(minWorkers, 1);
    this.maxWorkers = Math.max(this.minWorkers, maxWorkers);
    this.workerIdleLife = workerIdleLife;
  }

  public void run()
  {
    getNewWorker().run();
  }

  public synchronized void shutDown() throws IOException
  {
    this.serverSocket.close();
  }

  public int getPortNumber()
  {
    return this.serverSocket.getLocalPort();
  }

  protected abstract Worker makeNewWorker();

  private void setsocketTimeout(final int timeout) {
    try
    {
      this.serverSocket.setSoTimeout(timeout);
    }
    catch (final SocketException e) {}
  }

  private Worker getNewWorker()
  {
    if (this.liveWorkerCount++ == this.minWorkers) setsocketTimeout(this.workerIdleLife);
    return makeNewWorker();
  }

  private synchronized void startWork()
  {
    if (++this.workingWorkerCount == this.liveWorkerCount && this.liveWorkerCount < this.maxWorkers)
      new Thread(getNewWorker()).start();
  }

  private synchronized void endWork()
  {
    this.workingWorkerCount--;
  }

  private synchronized boolean workerMustDie()
  {

    if (this.liveWorkerCount > this.minWorkers && this.liveWorkerCount != this.workingWorkerCount + 1)
    {
      workerDies();
      return true;
    }
    return false;
  }

  private synchronized void workerDies()
  {
    if (--this.liveWorkerCount == this.minWorkers) setsocketTimeout(0);
  }


  protected abstract class Worker implements Runnable
  {
    public final void run()
    {
      try
      {
        while (true)
        {
          final Socket socket;

          try
          {
            socket = /*MinMLSocketServer.this.*/serverSocket.accept();

            try
            {
              try
              {
                MinMLSocketServer.this.startWork();

                Thread.yield(); // let a blocked worker thread do an accept()

                process(socket);
              }
              catch (final Exception e) {processingException(e);
              }
            }
            finally
            {
              try
              {
                socket.close();
              }
              catch (final IOException e) {}
              finally
              {
                MinMLSocketServer.this.endWork();
              }
            }
          }
          catch (final InterruptedIOException e)
          {
            if (MinMLSocketServer.this.workerMustDie()) return;
          }

        } // while(true)
      }
      catch (final Exception e)
      {
        operatingException(e);
        MinMLSocketServer.this.workerDies();
      }
    }

    protected abstract void process(Socket socket) throws Exception;

    protected void processingException(final Exception e) {
    }

    protected void operatingException(final Exception e) {
    }
  } // end Worker

  private ServerSocket serverSocket;
  protected final int minWorkers;
  protected final int maxWorkers;
  protected final int workerIdleLife;
  private int liveWorkerCount = 0;
  private int workingWorkerCount = 0;

} // MinMLSocketServer
